package com.csd.jwt.interceptor;

import com.csd.jwt.util.JWTUtil;
import org.slf4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @className: TokenInterceptor
 * @description:
 * @author: 刘子奇
 * @date: 2019/12/9 17:47
 **/
@Component
public class TokenInterceptor implements HandlerInterceptor {

    private final static Logger LOGGER = org.slf4j.LoggerFactory.getLogger(TokenInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        LOGGER.info("被拦截了");
        String token = request.getHeader("Authorization");
        //token验证
        LOGGER.info("token is :{}",token);
        if (token != null && !token.isEmpty()) {
            if (JWTUtil.verify(token)){
                LOGGER.info("token有效");
                //账户操作...
                return true;
            } else {
                LOGGER.info("token无效（超时或非法）");
                //验证错误,跳转到错误页面
                //response.sendRedirect(request.getContextPath()+"/twjd/error");
                response.setStatus(401);

                return false;
            }
        }
        LOGGER.info("token is empty");
        return false;
    }

}
